import { createStore } from 'vuex'

export default createStore({
  state: {
    user: null,
    token: localStorage.getItem('token') || '',
    cities: []
  },
  mutations: {
    SET_USER(state, user) {
      state.user = user
    },
    SET_TOKEN(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    SET_CITIES(state, cities) {
      state.cities = cities
    }
  },
  actions: {
    login({ commit }, { email, password }) {
      return new Promise((resolve, reject) => {
        // 调用 API 登录
        fetch('/api/users/login', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ email, password })
        })
        .then(res => res.json())
        .then(data => {
          if (data.status === 200) {
            commit('SET_TOKEN', data.token)
            commit('SET_USER', data.user)
            resolve(data)
          } else {
            reject(data.error)
          }
        })
        .catch(err => reject(err))
      })
    },
    logout({ commit }) {
      commit('SET_TOKEN', '')
      commit('SET_USER', null)
      localStorage.removeItem('token')
    },
    fetchCities({ commit, state }) {
      return new Promise((resolve, reject) => {
        fetch('/api/cities', {
          headers: { Authorization: `Bearer ${state.token}` }
        })
        .then(res => res.json())
        .then(data => {
          if (data.status === 200) {
            commit('SET_CITIES', data.cities)
            resolve(data)
          } else {
            reject(data.error)
          }
        })
        .catch(err => reject(err))
      })
    }
  }
})